<template>

<div>
    <Button type="primary" @click="add">添加</Button>
    <Button type="error" @click='del'>删除</Button> 
    <Input search  placeholder="请输入产品产品名称" style="width: auto"  @on-search="getName()" v-model="value"/>
    <Modal
        v-model="modal1"
        title="Common Modal dialog box title"
        footerHide>
        <Form ref="formValidate" :model="formValidate" :rules="ruleValidate" :label-width="80" >
        
            <FormItem label="产品名称" prop="name">
                <Input v-model="formValidate.name" placeholder="Enter your name"></Input>
            </FormItem>
            <FormItem label="产品类型" prop="goodstype">
                <Input    v-model="formValidate.goodstype" placeholder="Enter your goostype"></Input>
            </FormItem>
            <FormItem label="价格" prop="price">
                <Input    v-model="formValidate.price" placeholder="Enter your price"></Input>
            </FormItem>
            <FormItem label="库存" prop="stock">
                <Input   v-model="formValidate.stock"  placeholder="Enter your stock"></Input>
            </FormItem>
            <FormItem label="生产地" prop="maked">
                <Select v-model="formValidate.maked" placeholder="Select your maked">
                    <Option value="CN">中国</Option>
                    <Option value="US">美国</Option>
                    <Option value="EN">英国</Option>
                </Select>
            </FormItem>
            <FormItem label="生产日期">
                <Row>
                    <Col span="11">
                        <FormItem prop="date">
                            <DatePicker type="date" placeholder="Select date" v-model="formValidate.date"></DatePicker>
                        </FormItem>
                    </Col>
                    <Col span="2" style="text-align: center">-</Col>
                </Row>
            </FormItem>
            <FormItem label="是否进口" prop="import">
                <RadioGroup v-model="formValidate.import">
                    <Radio label="true">是</Radio>
                    <Radio label="false">否</Radio>
                </RadioGroup>
            </FormItem>
           <FormItem label="销售渠道" prop="sale">
                <CheckboxGroup v-model="formValidate.sale">
                    <Checkbox label="零售"></Checkbox>
                    <Checkbox label="网络"></Checkbox>
                    <Checkbox label="其他"></Checkbox>
                </CheckboxGroup>
            </FormItem> 
            <FormItem label="产品描述" prop="info">
                <Input v-model="formValidate.info" type="textarea" :autosize="{minRows: 2,maxRows: 5}" placeholder="Enter something..."></Input>
            </FormItem>
            <FormItem>
                <Button type="primary" @click="handleSubmit('formValidate')">Submit</Button>
                <Button @click="handleReset('formValidate')" style="margin-left: 8px">Reset</Button>
            </FormItem>
        </Form>
    </Modal>
     <Modal
        v-model="modal2"
        title="是否删除产品"
        @on-ok="ok"
        @on-cancel="cancel">
        <p>你确定要删除吗</p>
    </Modal>
     <Table border :columns="columns" :data="data"  @on-selection-change='getRemovesId' >
        <template slot-scope="{ row }" slot="name">
            <strong>{{ row.name }}</strong>
        </template>
        <template slot-scope="{ row, index }" slot="action">
            <Button type="primary" size="small" style="margin-right: 5px" @click="show(row._id)">修改</Button>
            <Button type="error" size="small" @click="del(row._id)">删除</Button>
            <Button type="error" size="small" @click="$router.push({path:'/comment/'+row._id})">评论</Button>
        </template>
         <div>
            <Table border ref="selection" :columns="columns" :data="data"></Table>
        </div>
    </Table>
    <Page :total="total" show-sizer @on-change='changPage' @on-page-size-change='changSize' :page-size-opts='[5,10,15,20]' :page-size='rows' />
</div>   
</template>
<script>
import { eventBus } from  "../../main.js";
import moment from 'moment'
    export default {
        data () {
            return {
                  modal1: false,
                  modal2:false,
                formValidate: {
                    name:'',
                    parentId:'',
                    goodstype:'',
                    date:'',
                    price:'',
                    stock:'',
                    maked:'',
                    sale:[],
                    import:'',
                    info:'',
                },
                ruleValidate: {
                    name: [
                        { required: true, message: 'The name cannot be empty', trigger: 'blur' }
                    ],
                    mail: [
                        { required: true, message: 'Mailbox cannot be empty', trigger: 'blur' },
                        { type: 'email', message: 'Incorrect email format', trigger: 'blur' }
                    ],
                    maked: [
                        { required: true, message: 'Please select the city', trigger: 'change' }
                    ],
                    import: [
                        { required: true, message: 'Please select import', trigger: 'change' }
                    ],
                    sale: [
                        { required: true, type: 'array', min: 1, message: 'Choose at least one sale', trigger: 'change' },
                    ],
                    date: [
                        { required: true, type: 'date', message: 'Please select the date', trigger: 'change' }
                    ],
                } ,
                columns: [
                       {
                        type: 'selection',
                        width: 60,
                        align: 'center'
                    },
                    {
                        title: '产品名称',
                        slot: 'name',
                        filters:'',
                    },
                    {
                        title: '产品类型',
                        key: 'goodstype'
                    },
                    {
                        title: '价格',
                        key: 'price',
                        align:'right',
                    },
                    {
                        title: '生产日期',
                        key: 'date',
                        align:'center',
                         render(h,columns){
                            let time=moment(columns.row.date).format("YYYY-MM-DD");
                            return h('span', time)
                        }
                    },
                    {
                        title: '库存',
                        key: 'stock',
                        align:'right'
                    },
                     {
                        title: '生产地',
                        key: 'maked',
                        align:'center'
                    },
                     {
                        title: '是否进口',
                        key: 'import',
                        align:'center',
                        render(h,columns) {
                            if(columns.row.import==true){
                                return h('span','进口')
                            }else{
                                return h('span','国产')
                            }
                        },
                    },
                    {
                        title: '销售渠道',
                        key: 'sale',
                        align:'right',
                        render(h,columns) {
                            let arr=columns.row.sale;
                            let str=arr.join(',')
                            return h('span',str)
                        },
                    },
                    {
                        title: '评论数',
                        key: 'reply',
                        align:'right'
                    },
                    {
                        title: '操作',
                        slot: 'action',
                        width: 180,
                        align: 'center',
                    }
                ],
                data:[],
                total:0,
                page:1,
                rows:5,
                removesId:[],
                bostop:true,
                parentId:'',
                value:'',
                delId:''

            }
        },
        methods: {
            //搜索
            getName(){
                 this.axios.post(`${config.dataBaseUrl}product//listname/${this.value}`,
                    {
                        page:this.page,
                        rows:this.rows,
                    })
                    .then(res=>{
                        this.data=res.data.rows
                        this.total=res.data.total
                    })  
                     
            },
            getBus(){
                eventBus.$on('parentId',(parentId)=>{  
                    this.parentId=parentId   
                    this.changPage(1)
                    this.changSize(5)
                    this.getList()
                    
                })
            },
            getList(){
                 this.axios.post(`${config.dataBaseUrl}product/list/${this.parentId}`,
                    {
                        page:this.page,
                        rows:this.rows,
                    })
                    .then(res=>{
                        this.data=res.data.rows
                        this.total=res.data.total
                    })  
                     
               
            },
            remove (id,index) {
                this.axios.delete(`${config.dataBaseUrl}product/${id}`)
                .then(res=>{
                });
                this.getList()
            },
            add(){
                this.modal1=true;
                this.handleReset('formValidate');
            },
            del(id){
                this.modal2=true;
                this.delId=id;
            },
            ok () {
                this.remove(this.delId);
                this.removes();
                this.$Message.info('删除成功');

            },
            cancel () {
                this.$Message.info('取消');
            },
            show(id){
                this.axios({
                    url:`${config.dataBaseUrl}product/${id}`,
                    method:'get',

                }).then(res=>{
                    res.data.import=res.data.import.toString();
                    this.formValidate=res.data;
                    this.modal1=true;
                })
            },
            //获取选中的_id
            getRemovesId(selection){
                this.removesId=[]
                for(var i=0;i<selection.length;i++){
                    this.removesId.push(selection[i]._id)
                }
            },
            handleSubmit (name) {
                this.$refs[name].validate((valid) => {
                    if (valid) {
                        if(this.formValidate._id){
                            //存在._id修改
                            this.axios({
                            url:`${config.dataBaseUrl}product/${this.formValidate._id}`,
                            method:'put',
                            data:this.formValidate
                            }).then(data=>{
                                this.getList();
                                this.modal1=false;
                            })

                        }else{
                            //不存在_id添加
                            console.log(this.formValidate)
                            this.axios({
                            url:`${config.dataBaseUrl}product`,
                            method:'post',
                            data:this.formValidate
                            })
                            .then(data=>{
                                this.getList();
                            }).catch(err=>{
                                console.log(err)
                            })
                            this.$Message.success('Success!');
                            this.modal1=false;
                            }
                    } else {
                        this.$Message.error('Fail!');
                    }
                })
            },
            handleReset (name) {
                this.$refs[name].resetFields();
            },
             //删除多条数据
            removes(){
                this.axios({
                    url:`${config.dataBaseUrl}product/removes`,
                    method:'post',
                    data:{
                        ids:this.removesId.toString()
                    }
                    })
                .then(res=>{
                    this.getList();
                }); 
             
            },
            changPage(page){
                this.page=page;
                this.getList()
            },
            changSize(rows){
                this.rows=rows,
                this.getList()
            }
        },
        watch:{
            modal1(m){
                //监听对话框 删除_id 判断修改和添加
                if(!m){
                delete this.formValidate._id
             }
            }
        },
        mounted(){
            this.getList();
            this.getBus();
            eventBus.$on('parentId',(parentId)=>{  
                this.formValidate.parentId=parentId;
            })
        }
    }
</script>